package com.vertx.demo;

import com.vertx.demo.utils.BaseUtils;
import io.reactivex.Single;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.mysqlclient.MySQLConnectOptions;
import io.vertx.reactivex.core.AbstractVerticle;
import io.vertx.reactivex.mysqlclient.MySQLPool;
import io.vertx.reactivex.sqlclient.Row;
import io.vertx.reactivex.sqlclient.RowIterator;
import io.vertx.reactivex.sqlclient.RowSet;
import io.vertx.reactivex.sqlclient.Tuple;
import io.vertx.sqlclient.PoolOptions;

/**
 * Created by zhangls on 2020/7/9.
 */
public class MySQLRxVerticle extends AbstractVerticle {

    private static final Logger LOGGER = LoggerFactory.getLogger(MySQLRxVerticle.class);

    private MySQLPool client;

    private static final String SQL = "SELECT USER_ID,REAL_NAME,EMAIL,PASS_WORD,PHONE_NUM,UPDATE_TIME FROM TB_USER WHERE STATUS=? AND USER_ID=?";

    private final MySQLConnectOptions connectOptions = new MySQLConnectOptions()
            .setCachePreparedStatements(true)
            .setPreparedStatementCacheMaxSize(100)
            .setConnectTimeout(5000)
            .setPort(3306)
            .setHost("127.0.0.1")
            .setDatabase("test")
            .setUser("root")
            .setPassword("123456")
            .setCharset("utf8mb4")
            .setCharacterEncoding("utf-8")
            .addProperty("useUnicode", "true")
            .addProperty("allowMultiQueries", "true")
            .addProperty("serverTimezone", "Hongkong");

    private final PoolOptions mySQLPoolOptions = new PoolOptions().setMaxSize(2);

    @Override
    public void start(Promise<Void> promise) throws Exception {

        client = MySQLPool.pool(vertx, connectOptions, mySQLPoolOptions);

        client.rxGetConnection().flatMap(conn -> {
            Single<RowSet<Row>> rowSetSingle = conn.rxPrepare(SQL).flatMap(ps -> {
                return ps.query().rxExecute(Tuple.of("1","1"));
            });
            return rowSetSingle.doAfterTerminate(conn::close);
        }).subscribe(rs -> {
            JsonArray res = new JsonArray();
            RowIterator<Row> rows = rs.value().iterator();
            while (rows.hasNext()) {
                JsonObject json = new JsonObject();
                Row row = rows.next();
                for (int i = 0; i < row.size(); i++) {
                    json.put(BaseUtils.underline2Camel(row.getColumnName(i), true), String.valueOf(row.getValue(i)));
                }
                res.add(json);
            }
            System.out.println(res.toString());
        }, Throwable::printStackTrace);
    }

    @Override
    public void stop(Promise<Void> stopPromise) throws Exception {
        client.close();
    }
}
